﻿#include "ssRedisPool.h"
#include "thread/ssThread.h"


namespace StarSeeker
{

ssRedisPool::ssRedisPool()
{
}

ssRedisPool::~ssRedisPool()
{
}

void ssRedisPool::Init(const char *hostname, int port, unsigned int count)
{
	SS_MUTEX_LOCK(m_lock)
		if (count && m_free.empty())
		{
			for (unsigned int i = 0; i < count; ++i)
			{
				ssRedisConnection* pConn = new ssRedisConnection(hostname, port);
				m_free.push_back(pConn);
				m_all.push_back(pConn);
			}
		}
	SS_MUTEX_UNLOCK(m_lock)
}

void ssRedisPool::WaitForExit()
{
	while (true)
	{
		SS_LOCK_GUARD(m_lock)
		if (m_all.empty())
		{
			break;
		}
		else if (m_free.size() == m_all.size())
		{
			for (size_t i = 0; i < m_all.size(); ++i)
			{
				delete m_all[i];
			}
			m_all.clear();
			m_free.clear();
			break;
		}
		else
		{
			ssThread::Sleep(500);
		}
	}
}

StarSeeker::ssRedisConnection* ssRedisPool::GetConnection()
{
	ssRedisConnection* ret = 0;
	SS_MUTEX_LOCK(m_lock)
		if (!m_free.empty())
		{
			ret = m_free.front();
			m_free.pop_front();
			ret->m_free = false;
		}
	SS_MUTEX_UNLOCK(m_lock)
	return ret;
}

void ssRedisPool::ReleaseConnection(ssRedisConnection* pConn)
{
	SS_MUTEX_LOCK(m_lock)
		pConn->m_free = true;
	m_free.push_back(pConn);
	SS_MUTEX_UNLOCK(m_lock)
}

}
